package Components
{
	import Providers.DragProvider;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	import mx.containers.Panel;
	import mx.events.FlexEvent;

	[Event(DraggablePanel.DRAG_STARTED)]
	public class DraggablePanel extends Panel
	{
		public static const DRAG_STARTED:String = "DragStarted";
			
		public function DraggablePanel()
		{
			super();
			addEventListener(FlexEvent.CREATION_COMPLETE, creationCompleteHandler);
		}
		
		//this is here so inheriters can override it.
		//Some ugliness now for less ugliness later.
		protected function creationCompleteHandler(evt:Event):void
		{
		}
		
		//offset is the distance from the initial click point on the panel to the panel's origin
		private var clickX:Number;
		private var clickY:Number;
		private var notifiedDragStarted:Boolean;
		
		protected function watchForDrag():void
		{
			clickX = parent.mouseX;
			clickY = parent.mouseY;
			notifiedDragStarted = false;
			parent.addEventListener(MouseEvent.MOUSE_MOVE, tbMouseMoveHandler);
			parent.addEventListener(MouseEvent.MOUSE_UP, tbMouseUpHandler);
		}
		
		private function tbMouseMoveHandler(evt:MouseEvent):void
		{
			var deltaX:Number = parent.mouseX - clickX
			var deltaY:Number = parent.mouseY - clickY;
			
			//if we haven't moved the mouse more than 3 pixels, its not a drag yet
			if(Math.abs(deltaX) < 3 && Math.abs(deltaY) < 3)
				return;
				
			//ok. now the drag has started. We'll hand it off to the 
			//	drag provider and stop listening
			stopListening();
			DragProvider.doDrag(this,true);
			dispatchEvent(new Event(DRAG_STARTED));
		}
		protected function tbMouseUpHandler(evt:Event):void
		{
			stopListening();
		}
		private function stopListening():void
		{
			parent.removeEventListener(MouseEvent.MOUSE_MOVE, tbMouseMoveHandler);
			parent.removeEventListener(MouseEvent.MOUSE_UP, tbMouseUpHandler);
		}
	}
}